package com.tj.admin.interceptors;

import com.fqgj.exception.common.ApplicationException;
import com.tj.admin.auth.anno.VisitorAccessible;
import com.tj.admin.auth.domain.Admin;
import com.tj.admin.auth.service.AdminService;
import com.tj.bo.common.conf.config.FileConfigUtil;
import com.tj.bo.common.conf.enums.RestCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;

/**
 * @program: binary-option
 * @description
 * @author: binary
 * @create: 2020-06-08 17:00
 **/
@Component
public class AdminAccessInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdminAccessInterceptor.class);

    @Autowired
    private FileConfigUtil fileConfigUtil;

    @Autowired
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Accept,X-Requested-With,remember-me,bid,basicParams,accessToken");

        //验证token
        String accessToken = request.getHeader("accessToken");
        //异常场景 报错
        if (StringUtils.isEmpty(accessToken)) {
            HandlerMethod handlerMethod = (HandlerMethod) o;
            VisitorAccessible visitorAccessible = handlerMethod.getMethodAnnotation(VisitorAccessible.class);
            if (visitorAccessible != null) {
                return true;
            }

            if (!request.getMethod().equals("OPTIONS")) {
                if (!handlerMethod.getMethod().getName().toUpperCase().equals("LOGIN")) {
                    throw new ApplicationException("need login to access");
                }
            }
        } else {

            if (StringUtils.isEmpty(accessToken)) {
                throw new ApplicationException("请登陆获取权限");
            }
            Admin byAccessToken = adminService.getByAccessToken(accessToken);

            if (byAccessToken == null) {
                throw new ApplicationException("无效的token");
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object handler, Exception e) throws Exception {
    }

    public AdminAccessInterceptor() {
    }

    private String getRequestBody(HttpServletRequest request) {

        String businessParams = "";
        try {
            RequestWrapper requestWrapper = new RequestWrapper(request);
            BufferedReader bufferedReader = requestWrapper.getReader();
            String line;
            StringBuilder requestBody = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                requestBody.append(line);
            }
            if (StringUtils.isNotEmpty(requestBody.toString())) {
                return new String(requestBody);
            }
        } catch (Exception e) {
            throw new ApplicationException(RestCodeEnum.PARAM_RESOLVE_ERROR);
        }
        return businessParams;
    }
}
